import React, { useEffect, useRef } from 'react';
import Chart from 'chart.js/auto';

export default function PieChart({
  title,
  data,
  labels,
  colors,
  type = 'doughnut', // 'pie' or 'doughnut'
  height = 300
}) {
  const chartRef = useRef(null);
  const chartInstance = useRef(null);

  const defaultColors = [
    'rgba(59, 130, 246, 0.8)', // blue
    'rgba(16, 185, 129, 0.8)', // green
    'rgba(139, 92, 246, 0.8)', // purple
    'rgba(249, 115, 22, 0.8)', // orange
    'rgba(236, 72, 153, 0.8)', // pink
    'rgba(245, 158, 11, 0.8)', // amber
    'rgba(6, 182, 212, 0.8)'   // cyan
  ];

  useEffect(() => {
    if (chartInstance.current) {
      chartInstance.current.destroy();
    }

    const ctx = chartRef.current.getContext('2d');
    
    // 如果没有提供足够的颜色，则重复使用默认颜色
    const chartColors = colors || defaultColors;
    const dataColors = data.map((_, index) => chartColors[index % chartColors.length]);

    chartInstance.current = new Chart(ctx, {
      type: type,
      data: {
        labels: labels,
        datasets: [
          {
            data: data,
            backgroundColor: dataColors,
            borderColor: dataColors.map(color => color.replace('0.8', '1')),
            borderWidth: 1,
            hoverOffset: 10,
          },
        ],
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        cutout: type === 'doughnut' ? '60%' : undefined,
        plugins: {
          legend: {
            position: 'bottom',
            labels: {
              padding: 15,
              boxWidth: 12,
              usePointStyle: true,
              pointStyle: 'circle',
              font: {
                size: 11,
              },
            },
          },
          tooltip: {
            backgroundColor: 'rgba(0, 0, 0, 0.7)',
            titleColor: '#fff',
            bodyColor: '#fff',
            padding: 10,
            displayColors: true,
            callbacks: {
              label: function(context) {
                const value = context.raw;
                const total = context.dataset.data.reduce((acc, data) => acc + data, 0);
                const percentage = ((value * 100) / total).toFixed(1) + '%';
                return `${context.label}: ${value} (${percentage})`;
              }
            }
          },
        },
        layout: {
          padding: {
            top: 5,
            bottom: 5,
            left: 10,
            right: 10,
          },
        },
      },
    });

    return () => {
      if (chartInstance.current) {
        chartInstance.current.destroy();
      }
    };
  }, [data, labels, colors, type]);

  return (
    <div className="bg-white p-5 rounded-lg shadow">
      <div className="flex justify-between items-center mb-4">
        <h3 className="text-lg font-semibold text-gray-800">{title}</h3>
      </div>
      <div style={{ height: `${height}px` }}>
        <canvas ref={chartRef} />
      </div>
    </div>
  );
} 